<?php
declare(strict_types=1);

namespace App\Console\Commands\Tasks;


use App\Enums\StreamerEnum;
use App\Repositories\Activity\MidAutumn2022\MidAutumn2022TaskRepository;
use App\Repositories\Streamer\StreamerRewardRepository;
use App\Repositories\Streamer\StreamerStatRepository;
use App\Repositories\Streamer\StreamerTaskRecordRepository;
use App\Repositories\Streamer\StreamerTaskRewardRepository;
use App\Resource\Streamer\Task\Resource;
use App\Services\Tools\ZeGoService;
use App\Services\Tools\CurlService;
use App\Services\Tools\WechatAppletService;
use App\Services\Tools\YlService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class TestCommand extends Command
{
    //命令名
    protected $signature = 'script:test';

    //命令描述:上周周星数据入库，并且发送周星奖励
    protected $description = 'script test';

    public function __construct()
    {
        parent::__construct();
    }

    //业务处理
    public function handle()
    {
        // $this->testTaskGenerate(); // 任务生成
        // $this->testTaskProgress(); // 任务进度
        // $this->testGetUserTask();
        // $this->testReceivePrizes();
        // $this->testStat();
        // $this->online();
        // $this->midAutumnTask();
        // $this->midAutumnTaskReceive();
        // $this->curl();
        // $this->ylPay();
        // $this->getWechatAccessToken();
        $this->generateWechatUrlScheme();
    }

    public function generateWechatUrlScheme()
    {
        $appId = env("PAY_YL_WX_APPLET_APPID");
        $secret = env("PAY_YL_WX_APPLET_SECRET");
        $server = new WechatAppletService($appId, $secret);


        $data = [
            "a" => 1,
            "b" => 2,
            "c" => 3,
        ];
        $res = $server->generateUrlScheme(http_build_query($data));
        print_r($res);
    }

    public function getWechatAccessToken()
    {
        $appId = env("PAY_YL_WX_APPLET_APPID");
        $secret = env("PAY_YL_WX_APPLET_SECRET");
        $server = new WechatAppletService($appId, $secret);
        $res = $server->getAccessToken();
        print_r($res);
    }

    public function ylPay()
    {
        $config = '{"appid": "wx6c2ecf902d2e4501", "money": "6.00", "appSecret": "fc20bd03c63462a5e72877dc6cad47d5", "notifyUrl": "http://ecd66a.natappfree.cc/api/payment/ylPayNotify", "appletPath": "", "merchantNum": "000000000245182", "appletOriginalId": "gh_8ca43cf9b09a", "orderNumExternal": "20220914513535556584"}';
        $config = json_decode($config, true);
        $server = new YlService($config);
        $res = $server->pay("ogx2z5TQJgWL3m9Izb74uNCrzrec", "11241241241", "1", "充值金额", "备注", "192.168.0.1");
    }


    public function curl()
    {
        $url = "https://api.weixin.qq.com/sns/jscode2session?";
        $params = [
            "appid" => "wx15a6aa8982dbdb49",
            "secret" => "fc20bd03c63462a5e72877dc6cad47d5",
            "js_code" => "021necII2mEgU94DfZmI2j3BFC0necl2",
            "grant_type" => "authorization_code",
        ];
        $url .= urldecode(http_build_query($params));
        echo $url . PHP_EOL;
        $result = CurlService::curl_get($url);

        print_r($result);
        // $this->midAutumnTaskReceive();
        $this->zeGoSongsTop();
        $this->searchSongs();
    }

    public function zeGoSongsTop()
    {
        $server = new ZeGoService(1, 1);
        $server->getSongsTop();
    }

    public function searchSongs()
    {
        $keywords = "我和我的祖国";
        $server = new ZeGoService(1, 1);
        $server->searchSongs($keywords);
    }

    public function midAutumnTask()
    {
        $userId = 4;
        $tasks = MidAutumn2022TaskRepository::getInstance()->tasks($userId);
        print_r($tasks->toArray());
        // $this->online();
    }

    public function midAutumnTaskReceive()
    {
        $taskId = 7;
        $userId = 4;
        MidAutumn2022TaskRepository::getInstance()->receive($taskId, $userId, 1);
    }


    public function testStat()
    {
        StreamerStatRepository::getInstance()->week(1);
    }

    public function testReceivePrizes()
    {
        $id = 1;
        $userId = 20;
        StreamerTaskRewardRepository::getInstance()->receive($id, $userId);
    }

    public function testGetUserTask()
    {
        $userId = 1;
        $models = StreamerTaskRecordRepository::getInstance()->userTasks($userId);
        print_r($models->toArray());
    }

    public function testTaskGenerate()
    {
        $userIds = [1, 4];
        StreamerTaskRecordRepository::getInstance()->generateDay($userIds);
        StreamerTaskRecordRepository::getInstance()->generateWeek($userIds);
    }

    public function testTaskProgress()
    {

        $userId = 4;
        $type = StreamerEnum::TASK_TYPE_RECEIVE_GIFTS;
        $count = 2000000;
        StreamerTaskRecordRepository::getInstance()->progress($userId, $type, $count);
    }

    public function online()
    {
        $yesterdayStart = Carbon::now()->addDays(-1)->startOfDay()->timestamp . PHP_EOL;
        $yesterdayEnd = Carbon::now()->addDays(-1)->endOfDay()->timestamp . PHP_EOL;

        $dayStart = Carbon::now()->startOfDay()->timestamp . PHP_EOL;

        $userIds = [4];
        foreach ($userIds as $userId){
            $second = 0;
            // 已记录的在线时长
            $records = app("model_room_join_time")->newQuery()
                ->where("user_id", $userId)
                ->where("join_time", ">=", $yesterdayStart)
                ->where("left_time", ">=", $yesterdayEnd)
                ->select(["left_time", "join_time", "total_seconds"])
                ->get();
            foreach ($records as $record){
                if($record->join_time < $dayStart){
                    $second += $record->left_time - $dayStart;
                }else{
                    $second += $record->total_seconds;
                }
            }

            // 未记录的在线时长
            $online = app("model_room_online_user")->newQuery()
                ->where("user_id", $userId)
                ->where("room_id", ">", 0)
                ->select(["join_time"])
                ->first();
            if($online){
                $second += time() - $online->join_time;
            }
            echo $second . PHP_EOL;
        }

        // print_r($users->toArray());
    }

}